package com.yangming.springboot.deepin.playTest;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;

/**
 * @创建人 ym
 * @创建时间 2021/4/22 0022
 * @描述
 **/
public class ForkAndJoinTest extends RecursiveTask<Integer> {

    private static final int THRESHOLD = 2;
    private int start;
    private int end;
    public ForkAndJoinTest(int start, int end){
        this.start = start;
        this.end = end;
    }
    @Override
    protected Integer compute(){
        int sum = 0;
        boolean canCompute = (end -start) <= THRESHOLD;
        if (canCompute){
            for (int i = start; i <= end; i++){
                sum += i;
            }
        }else{
            int middle = (start + end) / 2;
            ForkAndJoinTest leftTask = new ForkAndJoinTest(start, middle);
            ForkAndJoinTest rightTask = new ForkAndJoinTest(middle + 1, end);
            leftTask.fork();
            rightTask.fork();
            int leftResult = leftTask.join();
            int rightResult = rightTask.join();
            sum = leftResult + rightResult;
        }
        return sum;
    }
    public static void main(String[] args){
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkAndJoinTest forkAndJoinTest = new ForkAndJoinTest(1, 4);
        Future<Integer> result = forkJoinPool.submit(forkAndJoinTest);
        try{
            System.out.println(result.get());
        }catch(InterruptedException e){

        }catch(ExecutionException e){

        }
    }

}
